package org.jeecg.modules.demo.instoragemain.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.instoragedetail.service.IInStorageDetailService;
import org.jeecg.modules.demo.instoragemain.entity.InStorageMain;
import org.jeecg.modules.demo.instoragemain.service.IInStorageMainService;
import org.jeecg.modules.demo.outstoragedetail.service.IOutStorageDetailService;
import org.jeecg.modules.demo.outstoragemain.service.IOutStorageMainService;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 入库单主表
 * @Author: jeecg-boot
 * @Date: 2022-02-13
 * @Version: V1.0
 */
@Api(tags = "入库单主表")
@RestController
@RequestMapping("/instoragemain/inStorageMain")
@Slf4j
public class InStorageMainController extends JeecgController<InStorageMain, IInStorageMainService> {

    @Autowired
    private IInStorageMainService inStorageMainService;

    @Autowired
    private IOutStorageMainService outStorageMainService;

    @Autowired
    private IInStorageDetailService inStorageDetailService;

    @Autowired
    private IOutStorageDetailService outStorageDetailService;

    @Autowired
    private RedisUtils redisUtils;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     *
     * @param inStorageMain
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "入库单主表-分页列表查询")
    @ApiOperation(value = "入库单主表-分页列表查询", notes = "入库单主表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(InStorageMain inStorageMain,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        QueryWrapper<InStorageMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, inStorageMain, req.getParameterMap());
        Page<InStorageMain> page = new Page<>(pageNo, pageSize);
        IPage<InStorageMain> pageList = inStorageMainService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 查询入库单列表
     *
     * @param inStorageMain
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "查询入库单列表")
    @ApiOperation(value = "查询入库单列表", notes = "查询入库单列表")
    @GetMapping(value = "/searchList")
    public Result<?> searchList(InStorageMain inStorageMain,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }

        QueryWrapper<InStorageMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, inStorageMain, req.getParameterMap());
        Page<InStorageMain> page = new Page<>(pageNo, pageSize);
        Page<InStorageMain> pageList = inStorageMainService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param inStorageMain
     * @return
     */
    @AutoLog(value = "入库单主表-添加")
    @ApiOperation(value = "入库单主表-添加", notes = "入库单主表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody InStorageMain inStorageMain, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        String billNo = ToolsUtils.getBillNo("IS");
        inStorageMain.setBillNo(billNo);
        inStorageMain.setStoreId(storeId);
        inStorageMain.setPreparer(sysUser.getRealname());
        inStorageMainService.save(inStorageMain);
        return Result.OK(inStorageMain);
    }

    /**
     * 入库单-添加表头
     *
     * @param inStorageMain
     * @return
     */
    @AutoLog(value = "入库单-添加表头")
    @ApiOperation(value = "入库单-添加表头", notes = "入库单-添加表头")
    @PostMapping(value = "/addHead")
    public Result<?> addHead(@RequestBody InStorageMain inStorageMain) {
        inStorageMainService.save(inStorageMain);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param inStorageMain
     * @return
     */
    @AutoLog(value = "入库单主表-编辑")
    @ApiOperation(value = "入库单主表-编辑", notes = "入库单主表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody InStorageMain inStorageMain) {
        inStorageMainService.updateById(inStorageMain);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "入库单主表-通过id删除")
    @ApiOperation(value = "入库单主表-通过id删除", notes = "入库单主表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        inStorageMainService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "入库单主表-批量删除")
    @ApiOperation(value = "入库单主表-批量删除", notes = "入库单主表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.inStorageMainService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "入库单主表-通过id查询")
    @ApiOperation(value = "入库单主表-通过id查询", notes = "入库单主表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        InStorageMain inStorageMain = inStorageMainService.getById(id);
        if (inStorageMain == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(inStorageMain);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param inStorageMain
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InStorageMain inStorageMain) {
        //return super.exportXls(request, inStorageMain, InStorageMain.class, "入库单主表");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<InStorageMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, inStorageMain, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<InStorageMain> pageList = inStorageMainService.list(queryWrapper);

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "入库单主表"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, InStorageMain.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("入库单主表数据", "导出人:" + user.getRealname(), "入库单主表");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, InStorageMain.class);
    }

//	 @AutoLog(value = "出入库明细-分页列表查询")
//	 @ApiOperation(value="出入库明细-分页列表查询", notes="出入库明细-分页列表查询")
//	 @GetMapping(value = "/inoutPage")
//	 public Result<?> inoutPage(@RequestParam(name="commodityName", required = false) String commodityName,
//								@RequestParam(name="billNo", required = false) String billNo,
//								// "入库操作" / "出库操作"
//								@RequestParam(name="operateType", required = false) String operateType,
//								@RequestParam(name="beginTime", required = false) Date beginTime,
//								@RequestParam(name="endTime", required = false) Date endTime,
//								@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//								@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
//								HttpServletRequest req) {
//		 String token = TokenUtils.getTokenByRequest(req);
//		 String storeId = (String) redisUtils.get(RedisUtils.storeId +token);
//		 if(oConvertUtils.isEmpty(storeId)){
//			 return Result.error("请先到首页选择店铺");
//		 }
//		 Page<Map<String, Object>> page = new Page<>(pageNo, pageSize);
//		 Map<String, Object> params = new HashMap<>();
//		 params.put("storeId", storeId);
//		 params.put("commodityName", commodityName);
//		 params.put("billNo", billNo);
//		 params.put("operateType", operateType);
//		 params.put("beginTime", beginTime);
//		 params.put("endTime", endTime);
//		 IPage<Map<String, Object>> pageList = inStorageMainService.inoutPage(page, params);
//		 return Result.OK(pageList);
//	 }
}
